// pages/scanCode/scanCode.js
var verify = require('../../../../utils/verify-token.js')
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    type:[],
    material:[],
    isClear:false,
    count:0,
    over:false,
		validDate: '点击选择日期',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("options",options)
    var bunkerId = options.bunkerId
    var organId = options.organId
    var deviceId = options.deviceId
    var qrId = options.qrId
    var type1 = options.type
    if(options.hold=="true"){
      var hold = true
    }else{
      var hold = false
    }
    var meterialId = options.meterialId
    var count = options.count
    var meterialName = options.meterialName
    var token = app.globalData.token

    var type = []
    var tValue = []
    this.setData({
      curMaterial: meterialName,
      bunkerId:bunkerId,
      deviceId:deviceId,
      organId: organId,
      hold:hold,
      count:count,
      meterialId: meterialId,
      qrId:qrId,
      type1:type1,
      over:false
    })
    var that = this
    wx.request({
      url: app.globalData.baseUrl + 'getOrganListByBunkerId?bunkerId=' + bunkerId,
      header: {
        'AUTHORIZATION': token
      },
      success: function (res) {
        if (res.data.code == 60006) {
          verify.clearAll()
        } else if (res.data.code == 200) {
          console.log("机构", res)
          var dataList = res.data.data
          for (var i = 0; i < dataList.length; i++) {
            type.push(dataList[i].name)
            tValue.push(dataList[i].id)
            if (dataList[i].id == organId) {
              that.setData({
                curType: dataList[i].name
              })
            }
          }
          that.setData({
            type: type,
            tValue: tValue
          })
        }else{
          wx.showModal({
            title: '操作失败',
            content: res.data.message,
          })
        }
      }
    })

    var material = []
    var mValue = []
    var unit = ""
    wx.request({
      url: app.globalData.baseUrl + 'getMetListByBunkerIdAndOrganId?bunkerId=' + bunkerId + '&organId=' + organId,
      header: {
        'AUTHORIZATION': token
      },
      success: function (res) {
        if (res.data.code == 60006) {
          verify.clearAll()
        } else if (res.data.code == 200) { 
          console.log("原料", res)
          var dataList = res.data.data
          for (var i = 0; i < dataList.length; i++) {
            material.push(dataList[i].name)
            mValue.push(dataList[i].id)
            if (dataList[i].name == meterialName) {
              that.setData({
                meterialId: dataList[i].id
              })
            }
          }
          unit = dataList[0].unit
          that.setData({
            material: material,
            unit: unit,
            mValue: mValue
          })
        } else {
          wx.showModal({
            title: '操作失败',
            content: res.data.message,
          })
        }
      }
    })

  },

// 选择机构
  changeType:function(res){
    console.log(res.detail.value)
    var type = this.data.type[res.detail.value]
    var organId = this.data.tValue[res.detail.value]
    var bunkerId = this.data.bunkerId
    var token = app.globalData.token
    var that = this
    var material = []
    var mValue = []
    var unit = ""
    wx.request({
      url: app.globalData.baseUrl + 'getMetListByBunkerIdAndOrganId?bunkerId=' + bunkerId + '&organId=' + organId,
      header: {
        'AUTHORIZATION': token
      },
      success: function (res) {
        if (res.data.code == 60006) {
          verify.clearAll()
        } else if (res.data.code == 200) { 
          console.log("原料", res)
          var dataList = res.data.data
          for (var i = 0; i < dataList.length; i++) {
            material.push(dataList[i].name)
            mValue.push(dataList[i].id)
            // if (dataList[i].name == meterialName) {
            //   that.setData({
            //     meterialId: dataList[i].id
            //   })
            // }
          }
          unit = dataList[0].unit
          var curMaterial = material[0]
          var meterialId = mValue[0]
          that.setData({
            material: material,
            unit: unit,
            mValue: mValue,
            curMaterial: curMaterial,
            meterialId: meterialId
          })
        } else {
          wx.showModal({
            title: '操作失败',
            content: res.data.message,
          })
        }
      }
    })


    this.setData({
      curType:type,
      organId: organId
    })
  },
  // 选择原料
  changeMaterial:function(res){
    console.log(res.detail.value)
    var material = this.data.material[res.detail.value]
    var value = this.data.mValue[res.detail.value]
    this.setData({
      curMaterial:material,
      meterialId:value
    })
  },
  // 清空余料
  clear:function(res){
		let that = this;
		wx.showModal({
			title:'清空料仓',
			content:'确定要清空该料仓吗？',
			showCancel:true,
			success:function(res) {
				if(res.cancel){
					console.log('取消清空')
				}else{
					that.clearBunker();
				}
			},
			fail:function(res){
				
			}
		})
  },
	clearBunker:function(){
		let that = this;
		let deviceId = that.data.deviceId;
		let bunkerId = that.data.bunkerId;
		let token = app.globalData.token;
		let data = {
			deviceId:that.data.deviceId,
			bunkerId:that.data.bunkerId,
			organId:that.data.organId,
			meterialId:that.data.meterialId,
			unit:that.data.unit
		};
		wx.request({
		  url: app.globalData.baseUrl + 'device/'+deviceId+'/'+bunkerId+'/clearBunker',
		  header: {
				'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
		    'AUTHORIZATION': token
		  },
			method:'post',			
			data:data,
		  success: function (res) {
		    if (res.data.code == 60006) {
		      verify.clearAll()
		    } else if (res.data.code == 200) {
					wx.showToast({
						title:'操作成功',
						icon:'success',
						duration:2000
					})
				}else{
					wx.showToast({
						title:'操作失败',
						icon:'fail',
						duration:2000
					})
				}
			},
			fail() {
			  console.log("清空失败")
			}
		})
	},
	//有效期
	bindDateChange: function(e) {
    //console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      validDate: e.detail.value
    })
  },
  // 原料数量
  count:function(res){
    console.log(res)
    var count = res.detail.value
    this.setData({
      count:count
    })
  },
// 扫码补料
  scan:function(){
    var token = app.globalData.token
    var that = this
    wx.scanCode({
      success(res) {
        console.log(res.result)
        var length = res.result.length
        var qrId = "";
				let baseUrl = app.globalData.baseUrl;
        for (var i = 0; i < length; i++) {
          if (res.result[length - i - 1] == "=") {
            break;
          }
          qrId = res.result[length - i - 1] + qrId
        }
        wx.request({
          url: baseUrl+'feeding/getMeterialInfo?qrId=' + qrId,
          header: {
            'AUTHORIZATION': token
          },
          success: function (res) {
            if (res.data.code == 60006) {
              verify.clearAll()
            } else if (res.data.code == 200) {
              console.log("扫码补料", res)
              if (res.data.code == 200) {
                var count = res.data.data.count
                var meterialId = res.data.data.meterialId
                var organId = res.data.data.organId
                var curType = res.data.data.organName
                var curMaterial = res.data.data.meterialName
                that.setData({
                  count: count,
                  meterialId: meterialId,
                  organId: organId,
                  curType: curType,
                  curMaterial: curMaterial,
                  hold: true,
                  type1: "QRCODE",
                  qrId: qrId
                })
              } else {
                var message = res.data.message
                wx.showModal({
                  title: '',
                  content: message + "！！",
                })
              }
            } else {
              wx.showModal({
                title: '操作失败',
                content: res.data.message,
              })
            }
            
            
          }
        })
      },
      fail() {
        console.log("扫码失败")
      }
    }) 
  },

  // 确认补料
  add:function(){
    var that = this
    setTimeout(function () {
      var deviceId = that.data.deviceId
      var bunkerId = that.data.bunkerId
      var meterialId = that.data.meterialId
      var organId = that.data.organId
      var count = that.data.count
      var clear = that.data.isClear
      var qrId = that.data.qrId
      var type = that.data.type1
      var token = app.globalData.token
			let validDate = that.data.validDate=="点击选择日期"?"":that.data.validDate;
			let baseUrl = app.globalData.baseUrl;
      if (count == 0) {
        wx.showModal({
          title: '原料数量不能为空！！',
          content: '请输入实际补货数量！！',
        })
      } else {
        wx.request({
          url: baseUrl+'feeding/addMeterial?deviceId=' + deviceId + '&bunkerId=' + bunkerId +
            '&meterialId=' + meterialId + '&organId=' + organId + '&count=' + count + '&qrId=' + qrId + '&bunkerAddType=' + type + '&validDate=' + validDate,
          method: 'post',
          header: {
            'AUTHORIZATION': token
          },
          success: function (res) {
            if (res.data.code == 60006) {
              verify.clearAll()
            } else if (res.data.code == 200) {
              that.setData({
                over:true
              })
              wx.showToast({
                title: '补料成功',
                icon: 'success',
                duration: 3500
              })
            } else {
              wx.showToast({
                title: '补料失败!!',
                icon: 'none',
                duration: 3500
              })
            }
//             that.setData({
//               hold: true
//             })
          }
        })
      }
//       console.log("deviceId = " + deviceId)
//       console.log("bunkerId = " + bunkerId)
//       console.log("meterialId = " + meterialId)
//       console.log("organId = " + organId)
//       console.log("count = " + count)
//       console.log("clear = " + clear)
//       console.log("qrId = " + qrId)
//       console.log("type = " + type)

    }, 100)
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})